import { ConfigEnv, defineConfig, loadEnv, UserConfig } from 'vite'
import react from '@vitejs/plugin-react'
import {resolve} from 'path'
import { warppEnv } from './src/utils/getEnv'
import viteCompression from 'vite-plugin-compression'

// https://vite.dev/config/
export default defineConfig((mdoe:ConfigEnv):UserConfig=>{
  const env = loadEnv(mdoe.mode,process.cwd())
  const viteEnv = warppEnv(env)
  return {
    plugins: [
      react(),
      // 打包配置压缩
      viteEnv.VITE_USE_COMPRESS && viteCompression({
        verbose:true,
        disable:false,
        threshold:10240,
        algorithm:'gzip',
        ext:'.gz',
        deleteOriginFile:false,
        filter:/\.(js|mjs|json|css|html)$/i
      })
    ],
    // 配置别名
    resolve:{
      alias:{
        '@':resolve(__dirname,'src')
      }
    },
    server:{
      host:'0.0.0.0',
      port:viteEnv.VITE_PORT,
      open:viteEnv.VITE_OPEN,
      // 跨域配置
      proxy:{
        '/api':{
          target:viteEnv.VITE_API_URL,
          changeOrigin:true,
          rewrite:(path)=>path.replace(/^\/api/,'')
        }
      }
    },
    // 打包配置 esbuild 打包更快,但是不能去除console.log()  terser可以去除console.log()
    build:{
      outDir:'dist',
      // minify:'terser',
      // terserOptions:{
      //   compress:{
      //     drop_console:viteEnv.VITE_USE_CONSOLE,
      //     drop_debugger:true
      //   }
      // }
      minify:'esbuild',
      rollupOptions:{
        output:{
          chunkFileNames:'assets/js/[name]-[hash].js',
          entryFileNames:'static/js/[name]-[hash].js',
          assetFileNames:'static/[ext]/[name]-[hash].[ext]'
        }
      }
    }
  }
})
